from flask import Blueprint, request, jsonify
from src.models.database import db, HistoricalData
from src.services.data_service import DataService
import json

data_bp = Blueprint('data', __name__)
data_service = DataService()

@data_bp.route('/historical/import', methods=['POST'])
def import_historical_data():
    """导入历史数据"""
    try:
        if 'file' not in request.files:
            return jsonify({'code': 400, 'message': '未找到上传文件'}), 400
        
        file = request.files['file']
        if file.filename == '':
            return jsonify({'code': 400, 'message': '未选择文件'}), 400
        
        # 处理文件上传
        result = data_service.import_historical_data(file)
        
        return jsonify({
            'code': 200,
            'message': '数据导入成功',
            'data': result
        })
        
    except Exception as e:
        return jsonify({'code': 500, 'message': f'导入失败: {str(e)}'}), 500

@data_bp.route('/historical/query', methods=['GET'])
def query_historical_data():
    """查询历史数据"""
    try:
        # 获取查询参数
        filters = {}
        if request.args.get('business_unit'):
            filters['business_unit'] = request.args.get('business_unit')
        if request.args.get('metric_name'):
            filters['metric_name'] = request.args.get('metric_name')
        if request.args.get('year'):
            filters['year'] = request.args.get('year')
        if request.args.get('start_year'):
            filters['start_year'] = request.args.get('start_year')
        if request.args.get('end_year'):
            filters['end_year'] = request.args.get('end_year')
        
        # 查询数据
        records = data_service.query_historical_data(filters)
        
        return jsonify({
            'code': 200,
            'message': '查询成功',
            'data': {
                'records': records,
                'total': len(records)
            }
        })
        
    except Exception as e:
        return jsonify({'code': 500, 'message': f'查询失败: {str(e)}'}), 500

@data_bp.route('/historical/update', methods=['PUT'])
def update_historical_data():
    """更新历史数据"""
    try:
        data = request.get_json()
        record_id = data.get('id')
        
        if not record_id:
            return jsonify({'code': 400, 'message': '缺少记录ID'}), 400
        
        record = HistoricalData.query.get(record_id)
        if not record:
            return jsonify({'code': 404, 'message': '记录不存在'}), 404
        
        # 更新字段
        if 'value' in data:
            record.value = data['value']
        if 'unit' in data:
            record.unit = data['unit']
        
        record.updated_at = db.func.now()
        db.session.commit()
        
        return jsonify({
            'code': 200,
            'message': '更新成功',
            'data': record.to_dict()
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'code': 500, 'message': f'更新失败: {str(e)}'}), 500

@data_bp.route('/historical/delete', methods=['DELETE'])
def delete_historical_data():
    """删除历史数据"""
    try:
        record_id = request.args.get('id', type=int)
        
        if not record_id:
            return jsonify({'code': 400, 'message': '缺少记录ID'}), 400
        
        record = HistoricalData.query.get(record_id)
        if not record:
            return jsonify({'code': 404, 'message': '记录不存在'}), 404
        
        db.session.delete(record)
        db.session.commit()
        
        return jsonify({
            'code': 200,
            'message': '删除成功'
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'code': 500, 'message': f'删除失败: {str(e)}'}), 500

@data_bp.route('/historical/business-units', methods=['GET'])
def get_business_units():
    """获取所有业务单元"""
    try:
        units = data_service.get_business_units()
        return jsonify({
            'code': 200,
            'message': '获取成功',
            'data': units
        })
    except Exception as e:
        return jsonify({'code': 500, 'message': f'获取失败: {str(e)}'}), 500

@data_bp.route('/historical/metrics', methods=['GET'])
def get_metrics():
    """获取所有指标"""
    try:
        metrics = data_service.get_metrics()
        return jsonify({
            'code': 200,
            'message': '获取成功',
            'data': metrics
        })
    except Exception as e:
        return jsonify({'code': 500, 'message': f'获取失败: {str(e)}'}), 500

@data_bp.route('/historical/statistics', methods=['GET'])
def get_data_statistics():
    """获取数据统计信息"""
    try:
        stats = data_service.get_data_statistics()
        
        return jsonify({
            'code': 200,
            'message': '查询成功',
            'data': stats
        })
        
    except Exception as e:
        return jsonify({'code': 500, 'message': f'查询失败: {str(e)}'}), 500
